package com.chushouya.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

@Slf4j
public class PartnerSignUtils {
    /**
     * 生成签名
     * @param paramMap 加密参数
     * @param timestamp  系统时间戳, timestamp不参与请求参数ASCII排序
     * @param appKey 平台给合作商分配的appKey, appKey不参与请求参数ASCII排序，追加到参数字符最后
     * @return sign
     */
    public static String genMd5Sign(Map<String, Object> paramMap, final String timestamp, final String appKey) {
        Set<String> set = paramMap.keySet();
        TreeMap<String,String> treeMap = new TreeMap<>();
        for(String key: set){
            treeMap.put(key, paramMap.get(key).toString());
        }
        Set<Map.Entry<String, String>> setKey = treeMap.entrySet();
        StringBuilder sb = new StringBuilder();
        setKey.forEach(e -> {
            sb.append(e.getKey()).append(e.getValue());
        });
        // 追加timestamp、appKey到参数尾部，参与签名的生成
        sb.append("timestamp").append(timestamp);
        sb.append("appKey").append(appKey);
        final String data = sb.toString();
        log.info("====> DigestUtils.md5Hex: {}", data);
        final String sign = DigestUtils.md5Hex(data);
        log.info("====> genMd5Sign: {}", sign);
        return sign;
    }

//    public static void main(String[] args) {
//        String appKey = "YourPartnerAppKey";
//        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("categoryId", 100001L);
//        paramMap.put("brandId", 100002L);
//        paramMap.put("page", 1);
//        paramMap.put("size", 10);
//        paramMap.put("keywords", "关键词");
//        final String sign = PartnerSignUtils.genMd5Sign(paramMap, String.valueOf(Dates.getTimeNow().getTime()), appKey);
//        System.out.println(sign);
//    }
}
